package com.ananjt.utils.context;

import com.ananjt.system.entity.SpUser;
import com.ananjt.system.vo.SecurityUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class CurrentUser {

    public static String getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        OAuth2Authentication OAuth2Auth = (OAuth2Authentication) authentication;

        String userId = "";
        authentication = OAuth2Auth.getUserAuthentication();
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof SecurityUserDetails) {
                return ((SecurityUserDetails) principal).getId();
            }
            UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
            Map<String,Object> map = (Map) authenticationToken.getDetails();
            map = (Map) map.get("principal");
            return map.get("id")+"";
        }
        return userId;
    }

    public static String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userName = "";
        if (authentication != null && authentication.getPrincipal() instanceof SpUser) {
            SpUser user = (SpUser) authentication.getPrincipal();
            userName = user.getUserName();
        }
        return userName;
    }
}
